package com.wty.config;

import com.wty.DynamicDataSource;
import com.wty.common.DataSources;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangtengyu
 * @Create 2018-08-30-18:50
 */
@Configuration
@MapperScan(basePackages = "com.wty.dao")
public class MybatisConfig {

    //注入两个定义好的数据源

    @Autowired
    @Qualifier(DataSources.MASTER_DB)
    private DataSource masterDs;

    @Autowired
    @Qualifier(DataSources.SLAVE_DB)
    private DataSource slaveDs;

    @Bean
    public DataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource =new DynamicDataSource();

        dynamicDataSource.setDefaultTargetDataSource(masterDs);

        Map<Object,Object> dsMap= new HashMap<>();
        dsMap.put(DataSources.MASTER_DB,masterDs);
        dsMap.put(DataSources.SLAVE_DB,slaveDs);
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }



    @Bean
    @ConfigurationProperties(prefix = "mybatis")
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
//        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappers/*.xml"));
        return sqlSessionFactoryBean;
    }












}
